package org.nmgyjt.springboot.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * @author undefine
 */
public class SerializeUtil {
	private static String DATE_TIME_PATTERN2 = "yyyy-MM-dd HH:mm:ss";
	private static String APP_APPEND_STR = "appkey=" ;
	private static String RANDOM_STR = "&random=" ;

	public static ObjectMapper get() {
		return getObjectMapper().get();
	}

	/**
	 * 注意日期格式序列化和反序列化的时候yyyy-MM-dd HH:mm:ss,如果不同，请创建自己的objectMapper
	 */
	private static ThreadLocal<ObjectMapper> getObjectMapper() {
		return new ThreadLocal<ObjectMapper>() {
			@Override
			protected ObjectMapper initialValue() {
				return createObjectMapper();
			}
		};
	}

	private static ObjectMapper createObjectMapper(SimpleDateFormat des, SimpleDateFormat ser) {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.setSerializationInclusion(Include.NON_NULL);
		objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_PATTERN2));
		/**
		 * 因为objectmapper默认是使用UTC时间，但是我们创建的时间是使用默认时区
		 */
		objectMapper.setTimeZone(TimeZone.getDefault());
		return objectMapper;
	}

	/**
	 * 默认使用yyyy-MM-dd HH:mm:ss序列化和反序列化日期
	 * 
	 * @return
	 */
	private static ObjectMapper createObjectMapper() {
		SimpleDateFormat dateTimeSdf2 = new SimpleDateFormat(DATE_TIME_PATTERN2);
		return createObjectMapper(dateTimeSdf2, dateTimeSdf2);
	}

	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return get().getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}

	public static void writeResponse(HttpServletResponse response, Object data) {
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		try {
			Writer writer = response.getWriter();
			writer.write(get().writeValueAsString(data));
			writer.flush();
			writer.close();
		} catch (IOException e2) {

		}
	}
}
